package com.shop.shopserver.service.impl;

import cn.hutool.db.sql.Order;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.shopcommon.context.SecurityContext;
import com.shop.shopcommon.enumeration.OrderStatusType;
import com.shop.shopcommon.enumeration.PayStatusType;
import com.shop.shopcommon.result.Result;
import com.shop.shoppojo.dto.OrderDTO;
import com.shop.shoppojo.entity.Goods;
import com.shop.shoppojo.entity.User;
import com.shop.shoppojo.entity.UserOrder;
import com.shop.shoppojo.vo.OrderDataVO;
import com.shop.shoppojo.vo.OrderGoodsVO;
import com.shop.shoppojo.vo.OrderListVO;
import com.shop.shoppojo.vo.OrderVO;
import com.shop.shopserver.mapper.GoodsMapper;
import com.shop.shopserver.mapper.OrderMapper;
import com.shop.shopserver.mapper.UserMapper;
import com.shop.shopserver.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 查询订单
 */

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, UserOrder> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private UserMapper userMapper;

    //根据缓存中的user_id查询订单
    public Result<OrderVO> getMyOrderList(OrderDTO orderDTO){
        //判断查询类型 all-全部，payment-待支付，delivery-待发货，received-待收货，comment-待评价
        if (orderDTO.getDataType() ==null){
            //dataType为空默认all
            orderDTO.setDataType("all");
        }

        Page<UserOrder> page = new Page<>(orderDTO.getPage(), orderDTO.getPageSize());
        log.info("order获取的session的userId:"+getUserIdByUsername().getId());
        List<UserOrder> UserOrderList = switch (orderDTO.getDataType()) {
            case "all" ->
                //all-全部
                    orderMapper.selectPage(page,new LambdaQueryWrapper<UserOrder>()
                            .eq(UserOrder::getUserId, getUserIdByUsername().getId())
                            .orderByDesc(UserOrder::getCreateTime))
                            .getRecords();
            case "payment" ->
                //payment-待支付
                    orderMapper.selectPage(page,new LambdaQueryWrapper<UserOrder>()
                            .eq(UserOrder::getUserId, getUserIdByUsername().getId())
                            .eq(UserOrder::getOrderStatus, OrderStatusType.UNPAID)
                            .eq(UserOrder::getPayStatus, PayStatusType.NOT_PAY)
                            .orderByDesc(UserOrder::getCreateTime))
                            .getRecords();
            case "delivery" ->
                //delivery-待发货
                    orderMapper.selectPage(page,new LambdaQueryWrapper<UserOrder>()
                            .eq(UserOrder::getUserId, getUserIdByUsername().getId())
                            .eq(UserOrder::getOrderStatus, OrderStatusType.UNSHIPPED)
                            .eq(UserOrder::getPayStatus, PayStatusType.PAY)
                            .orderByDesc(UserOrder::getCreateTime))
                            .getRecords();
            case "received" ->
                //received-待收货
                    orderMapper.selectPage(page,new LambdaQueryWrapper<UserOrder>()
                            .eq(UserOrder::getUserId, getUserIdByUsername().getId())
                            .eq(UserOrder::getOrderStatus, OrderStatusType.UNRECEIVED)
                            .eq(UserOrder::getPayStatus, PayStatusType.PAY)
                            .orderByDesc(UserOrder::getCreateTime))
                            .getRecords();
            case "comment" ->
                //comment-待评价
                    orderMapper.selectPage(page,new LambdaQueryWrapper<UserOrder>()
                            .eq(UserOrder::getUserId, getUserIdByUsername().getId())
                            .eq(UserOrder::getOrderStatus, OrderStatusType.UNCOMMENT)
                            .eq(UserOrder::getPayStatus, PayStatusType.PAY)
                            .orderByDesc(UserOrder::getCreateTime))
                            .getRecords();
            default -> null;
        };
        assert UserOrderList != null;
        List<UserOrder> reversedUserOrderList = new ArrayList<>(UserOrderList);
        //在订单查询的信息基础上添加对应的商品信息
        List<OrderDataVO> orderDataVOList = reversedUserOrderList.stream()
                .map(order -> {
                    Goods goods=goodsMapper.selectOne(new LambdaQueryWrapper<Goods>().eq(Goods::getId,order.getGoodsId()));
                    OrderGoodsVO orderGoodsVO=new OrderGoodsVO();
                    OrderDataVO orderDataVO=new OrderDataVO();
                    BeanUtils.copyProperties(order, orderDataVO);
                    orderDataVO.setId(order.getId().toString());
                    BeanUtils.copyProperties(goods, orderGoodsVO);
                    List<OrderGoodsVO> goodsList = Collections.singletonList(orderGoodsVO);
                    orderDataVO.setGoods(goodsList);
                    return  orderDataVO;
                })

                .toList();
        System.out.println("orderDataVOList:"+orderDataVOList);


        //设置到list

        OrderListVO orderListVO= OrderListVO
                .builder()
                .total(orderDataVOList.size())
                .data(orderDataVOList)
                .build();

        //包装
        OrderVO orderVO=OrderVO
                .builder()
                .list(orderListVO)
                .build();
        return Result.success(orderVO,"返回成功");
    }

    /**
     * 根据用户名查询用户id
     * @return
     */
    private User getUserIdByUsername() {
        String username = SecurityContext.getUsername();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
                .select(User::getId)
                .eq(User::getUsername, username);
        User user = userMapper.selectOne(queryWrapper);
        System.out.println("user" + user);
        return user;
    }
}
